<script setup lang="ts">
  import SingleAddress from '@/components/business/address/single-address/SingleAddress.vue'
  import { computed, ref } from 'vue'
  import useAddParser from '@/services/common/useAddParser'
  import { useGetCustomerOptions } from '@/services/pages/customer/useGetOptions'
  import _ from 'lodash'
  import { FormInstance } from 'element-plus'
  import { useGetMainContactPersonOptionList } from '@/services/pages/user/useUser'

  const { addrParseResult, addrParseLoading, addrParse } = useAddParser()
  const {
    options: customerOptions,
    loading: getCustomerOptionsLoading,
    getOptionsParam: getCustomerOptionsParam,
    getOptions: getCustomerOptions,
  } = useGetCustomerOptions()
  const {
    optionList: sendRepairUserOptionList,
    getOptionListParam: getSendRepairUserOptionListParam,
    getOptionListLoading: getSendRepairUserOptionListLoading,
    getOptionList: getSendRepairUserOptionList,
  } = useGetMainContactPersonOptionList()

  defineOptions({
    name: 'CustomerInfoReturnFactoryCreate',
  })

  type Form = Pick<
    ReturnFactoryAPIRequest.Create,
    | 'address'
    | 'area'
    | 'city'
    | 'otherPhone'
    | 'phone'
    | 'province'
    | 'repairCompanyId'
    | 'repairCompanyName'
    | 'repairCompanyPhone'
    | 'sendForRepairPhone'
    | 'sendForRepairUsername'
    | 'userId'
    | 'username'
  > & { customerTakePieceMode: 1 | 2 }

  const emits = defineEmits<{
    (e: 'change-user', value: Form): void
    (e: 'change-take-package-method', value: 1 | 2): void
  }>()

  // 报单公司弹出框显示状态
  const createOrderCompanySelectPopoverVisible = ref(false)

  // 地址识别文本
  const addrParserVal = ref('')

  // 用户选择弹出框显示状态
  const customerSelectPopoverVisible = ref(false)

  // 地址选择组件实例
  const singleAddressRef = ref<InstanceType<typeof SingleAddress> | null>(null)

  // 表单
  const form = ref<Form>({
    address: '',
    area: '',
    city: '',
    province: '',
    phone: '',
    username: '',
    userId: '',
    otherPhone: '',
    customerTakePieceMode: 2,
    repairCompanyId: '',
    repairCompanyName: '',
    repairCompanyPhone: '',
    sendForRepairPhone: '',
    sendForRepairUsername: '',
  })

  // 表单验证规则
  const rules = ref({
    userId: [{ required: true, message: '请选择公司', trigger: ['change', 'blur'] }],
    // address: [{ required: true, message: '请输入详细地址', trigger: ['change', 'blur'] }],
    // phone: [
    //   { required: true, message: '请输入手机号', trigger: ['change', 'blur'] },
    //   {
    //     validator: (rule, value, callback) => {
    //       if (!verifyPhone(form.value.phone)) {
    //         callback(new Error('格式不正确'))
    //         return
    //       }
    //       callback()
    //     },
    //     trigger: ['change', 'blur'],
    //   },
    // ],
    // otherPhone: [
    //   {
    //     validator: (rule, value, callback) => {
    //       if (form.value.otherPhone && !verifyPhone(form.value.otherPhone)) {
    //         callback(new Error('格式不正确'))
    //         return
    //       }
    //       callback()
    //     },
    //     trigger: ['change', 'blur'],
    //   },
    // ],
    // username: [{ required: true, message: '请输入客户名称', trigger: ['change', 'blur'] }],
    // province: [
    //   { required: true, message: '请选择地址', trigger: ['change', 'blur'] },
    //   {
    //     validator: (rule, value, callback) => {
    //       if (!form.value.province || !form.value.area || !form.value.city) {
    //         callback(new Error('请选择地址'))
    //         return
    //       }
    //       callback()
    //     },
    //     trigger: ['change', 'blur'],
    //   },
    // ],
  })

  // 地址回显，用于给SingleAddress组件显示选择的地址
  const addressEcho = computed(() => {
    return {
      province: form.value.province,
      area: form.value.area,
      city: form.value.city,
      town: '',
    }
  })

  // 表单组件实例
  const formInstance = ref<FormInstance | null>(null)

  /**
   * 获取公司下拉选项
   */
  const handleGetCustomerOptions = _.debounce((keyword: string) => {
    if (getCustomerOptionsParam.value.name !== keyword) {
      getCustomerOptionsParam.value.name = keyword
      getCustomerOptions()
    }
  }, 600)

  /**
   * 触发用户更新事件
   */
  const emitsChangeUser = () => {
    emits('change-user', form.value)
  }

  /**
   * 清空公司信息
   */
  const clearCustomerInfo = () => {
    form.value = {
      address: '',
      area: '',
      city: '',
      province: '',
      phone: '',
      username: '',
      userId: '',
      otherPhone: '',
      customerTakePieceMode: 2,
      repairCompanyId: '',
      repairCompanyName: '',
      repairCompanyPhone: '',
      sendForRepairPhone: '',
      sendForRepairUsername: '',
    }
    customerSelectPopoverVisible.value = false
    emitsChangeUser()
  }

  /**
   * 选择公司
   * @param {string} customerOptionId - 公司下拉选项
   */
  const handleSelectCustomer = (customerOptionId: string) => {
    const customer = customerOptions.value.find((item) => item.userId === customerOptionId)
    if (customer) {
      Object.assign(form.value, {
        address: customer.address,
        province: customer.province,
        city: customer.city,
        area: customer.area,
        userId: customer.userId,
        username: customer.username,
        phone: customer.phone,
        otherPhone: form.value.otherPhone,
        customerTakePieceMode: form.value.customerTakePieceMode,
      })
      emitsChangeUser()
    }
  }

  /**
   * 地址识别方法
   */
  const addrParser = async () => {
    if (!addrParserVal.value.trim()) return
    await addrParse(addrParserVal.value.trim())
    if (addrParseResult.value) {
      Object.assign(form.value, {
        province: addrParseResult.value.province,
        city: addrParseResult.value.city,
        area: addrParseResult.value.area,
        userId: '',
        username: addrParseResult.value.username,
        phone: addrParseResult.value.phone,
        address: addrParseResult.value.address,
        otherPhone: form.value.otherPhone,
        customerTakePieceMode: form.value.customerTakePieceMode,
      })
    }
    emitsChangeUser()
  }

  /**
   * 更新省市区
   * @param {Object} address - 省市区集合
   * @param {String} address.province - 省
   * @param {String} address.area - 市
   * @param {String} address.city - 区
   * @param {String} address.town - 镇
   */
  const handleChangeProvinceAreaCity = (address: {
    province: string
    area: string
    city: string
    town: string
  }) => {
    form.value.province = address.province
    form.value.area = address.area
    form.value.city = address.city
    emitsChangeUser()
  }

  /**
   * 用户手机号更新事件
   */
  const handleInputPhone = _.debounce(() => {
    emitsChangeUser()
  }, 600)

  /**
   * 详细地址更新事件
   */
  const handleInputDetailAddress = _.debounce(() => {
    emitsChangeUser()
  }, 600)

  /**
   * 取件方式更新事件
   */
  const onChangeTakePackageMethod = () => {
    emits('change-take-package-method', form.value.customerTakePieceMode)
  }

  /**
   * 报单公司信息清除事件
   */
  const onCreateOrderCompanyInfoClear = () => {
    form.value.repairCompanyId = ''
    form.value.repairCompanyName = ''
    form.value.repairCompanyPhone = ''
  }

  /**
   * 报单公司输入事件
   */
  const handleCreateOrderCompanyInput = _.debounce((keyword: string) => {
    if (keyword.trim()) {
      createOrderCompanySelectPopoverVisible.value = true
      getSendRepairUserOptionListParam.value.name = form.value.repairCompanyName
      getSendRepairUserOptionList()
    }
  }, 500)

  /**
   * 报单公司更新事件
   * @param {UserMainContactPersonOption} sendRepairUser - 报单公司
   */
  const handleCreateOrderCompanyChange = (sendRepairUser: UserMainContactPersonOption) => {
    form.value.repairCompanyName = sendRepairUser.name
    form.value.repairCompanyId = sendRepairUser.userId
    form.value.repairCompanyPhone = sendRepairUser.phone
  }

  defineExpose({
    getCustomerOptions,
    getForm: async () => {
      if (formInstance.value) {
        try {
          await formInstance.value.validate()
          return form.value
        } catch (error) {
          return null
        }
      }
      return null
    },
    setForm: (_form: Form) => {
      form.value = _form
    },
  })
</script>

<template>
  <div v-loading="addrParseLoading" class="return-factory-customer-info">
    <div class="title">寄修人信息</div>
    <div class="form">
      <el-form
        ref="formInstance"
        label-width="85"
        inline-message
        :model="form"
        :rules="rules"
        label-position="top"
      >
        <div class="config">
          <!-- 地址识别 -->
          <el-form-item label="地址识别" class="address-parser">
            <el-input
              v-model.trim="addrParserVal"
              type="textarea"
              resize="both"
              maxlength="200"
              placeholder="粘贴整段信息到此文本框如：张三，15815151515，北京市市辖区石景山区中山路25号"
              show-word-limit
            />
            <h-button type="primary" @click="addrParser">识别</h-button>
          </el-form-item>

          <!-- 取件方式 -->
          <el-form-item label="取件方式">
            <el-select
              v-model="form.customerTakePieceMode"
              placeholder="请选择取件方式"
              @change="onChangeTakePackageMethod"
            >
              <el-option label="自取" :value="1" />
              <el-option label="快递寄回" :value="2" />
            </el-select>
          </el-form-item>
        </div>
        <div class="customer-info">
          <!-- 客户名称 -->
          <el-form-item label="客户名称" prop="userId">
            <el-select
              v-model="form.userId"
              placeholder="请选择客户"
              clearable
              filterable
              :filter-method="handleGetCustomerOptions"
              :loading="getCustomerOptionsLoading"
              @clear="clearCustomerInfo"
              @change="handleSelectCustomer"
            >
              <el-option
                v-for="(customerOption, customerOptionIndex) in customerOptions"
                :key="customerOptionIndex"
                :label="customerOption.name"
                :value="customerOption.userId || ''"
              />
            </el-select>
          </el-form-item>

          <!-- 公司地址 -->
          <el-form-item label="公司地址" prop="province">
            <SingleAddress
              ref="singleAddressRef"
              :address="addressEcho"
              @change="handleChangeProvinceAreaCity"
            />
          </el-form-item>

          <!-- 详细地址 -->
          <el-form-item label="公司详细地址" prop="address">
            <el-input
              v-model.trim="form.address"
              type="textarea"
              placeholder="请输入详细地址"
              resize="both"
              maxlength="200"
              show-word-limit
              @input="handleInputDetailAddress"
            />
          </el-form-item>
        </div>
        <div class="contact-info">
          <!-- 报单人信息 -->
          <el-form-item label="报单人信息" prop="sendForRepairUsername">
            <el-input
              v-model.trim="form.sendForRepairUsername"
              placeholder="请输入报单人信息"
              maxlength="50"
            />
          </el-form-item>

          <!-- 报单人电话 -->
          <el-form-item label="报单人电话" prop="sendForRepairPhone">
            <el-input
              v-model.trim.number="form.sendForRepairPhone"
              placeholder="请输入报单人电话"
              maxlength="11"
              @input="handleInputPhone"
            />
          </el-form-item>

          <!-- 快递单号 -->
          <el-form-item label="快递单号：" prop="otherPhone">
            <el-input v-model.trim="form.otherPhone" placeholder="请输入快递单号" />
          </el-form-item>
        </div>
        <div class="create-order-company-info">
          <el-form-item label="报单公司" prop="repairCompanyName" class="top">
            <el-popover :visible="createOrderCompanySelectPopoverVisible" :width="370">
              <template #reference>
                <el-input
                  v-model.trim="form.repairCompanyName"
                  placeholder="请输入报单公司"
                  clearable
                  @clear="onCreateOrderCompanyInfoClear"
                  @input="handleCreateOrderCompanyInput"
                  @blur="createOrderCompanySelectPopoverVisible = false"
                />
              </template>

              <el-table
                v-loading="getSendRepairUserOptionListLoading"
                :max-height="300"
                :border="true"
                :data="sendRepairUserOptionList"
                @row-click="handleCreateOrderCompanyChange"
              >
                <!-- 序号 -->
                <el-table-column label="序号" type="index" :width="50" />

                <!-- 报单客户名称 -->
                <el-table-column
                  label="报单客户名称"
                  :min-width="100"
                  show-overflow-tooltip
                  prop="name"
                />

                <!-- 报单公司电话 -->
                <el-table-column
                  label="报单公司电话"
                  :width="120"
                  show-overflow-tooltip
                  prop="phone"
                />
              </el-table>
            </el-popover>
          </el-form-item>

          <!-- 报单公司电话 -->
          <el-form-item class="customer_phone top" label="报单公司电话" prop="repairCompanyPhone">
            <el-input
              v-model.trim.number="form.repairCompanyPhone"
              maxlength="11"
              placeholder="请输入报单公司电话"
            />
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style scoped lang="scss">
  :deep(.el-form-item) {
    margin: 0;
  }

  .user-select-popover-trigger-el {
    cursor: pointer;
    height: 28px;
    line-height: 28px;
    display: flex;
    align-items: center;
  }

  .user-select-wrapper {
    .close-btn {
      display: flex;
      justify-content: flex-end;
      margin-bottom: 12px;

      .iconfont {
        width: 24px;
        height: 24px;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;

        &:hover {
          background-color: #f5f7fa;
        }
      }
    }

    .user-select {
      max-height: 350px;
      overflow: auto;

      .customer-info {
        display: flex;
        height: 32px;
        column-gap: 12px;
        cursor: pointer;

        &:hover {
          background-color: #f5f7fa;
        }

        .customer-name {
          line-height: 32px;
          width: 160px;
          text-align: right;
        }

        .customer-phone {
          line-height: 32px;
        }
      }
    }
  }

  .return-factory-customer-info {
    display: flex;
    flex-direction: column;

    .title {
      font-size: 14px;
      padding-left: 6px;
      font-weight: bold;
      border-left: 3px solid $primaryColor;
    }

    .form {
      :deep(.el-form) {
        display: grid;
        grid-template-columns: repeat(auto-fill, 440px);
        column-gap: 100px;
        margin-top: 18px;
        row-gap: 18px;
        padding: 0 38px;

        .el-form-item {
          .el-form-item__label {
            height: 16px;
            line-height: 16px;
            margin: 0 0 3px 0;
          }

          .el-form-item__content {
            width: 100%;

            .el-form-item__error {
              padding: 0;
              margin: 3px 0 0 0;
            }
          }
        }

        .address-parser {
          .el-form-item__content {
            display: flex;
            flex-direction: row;
            column-gap: 12px;
            align-items: center;
            height: fit-content;

            .el-textarea {
              flex: 1;

              .el-textarea__inner {
                width: 100% !important;
                min-height: 95px !important;
                max-height: 140px !important;
              }
            }
          }
        }

        .customer-info,
        .contact-info,
        .config,
        .create-order-company-info {
          display: flex;
          flex-direction: column;
          row-gap: 18px;
        }

        .config {
          .el-select {
            width: 382px;
          }
        }

        .customer-name-phone {
          .el-input-group__append {
            width: 30px;
            padding: 0;

            .el-select__wrapper {
              padding: 0;
              justify-content: center;

              &:hover {
                box-shadow: 0 1px 0 0 var(--el-input-border-color) inset,
                  0 -1px 0 0 var(--el-input-border-color) inset,
                  -1px 0 0 0 var(--el-input-border-color) inset !important;
              }

              .el-select__selection {
                display: none;
              }

              .el-select__suffix {
                .el-icon {
                  color: #a8abb2;
                }
              }
            }
          }
        }

        .customer-info {
          .el-textarea {
            .el-textarea__inner {
              width: 100% !important;
              height: 28px;
              min-height: 28px !important;
              max-height: 130px !important;
            }
          }
        }
      }
    }
  }
</style>
